<?php
namespace kdcs;

use app\admin\model\ExpressModel;

Class Spider{

    public function doLogin($username, $password, $code, $cookie){
        $url="https://kdcs.zto.cn/user/login";
        $param = [
            "username"=> $username,
            "password"=> $password,
            "verifyCode"=> $code,
        ];
        // $data = json_encode($param);
        $data = http_build_query($param);
        $headers = array(
            "Host: kdcs.zto.cn",
            "Content-Type: application/x-www-form-urlencoded",
            "Accept: application/json, text/plain, */*",
            "Accept-Encoding: gzip, deflate, br",
            "Connection: keep-alive",
            "Cookie: " . $cookie,
            "Referer: https://kdcs.zto.cn/",
            "User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0",
        );
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, true);
        // curl_setopt($ch, CURLOPT_NOBODY, $getBody);
        ob_start();
        $res = curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        $httpInfo = curl_getinfo($ch);
        $header = substr($res, 0, $httpInfo['header_size']);
        $body = substr($res, $httpInfo['header_size']);
        $json = json_decode($body);
        if($httpInfo['http_code'] == 200){
            return ['head' => $header, 'body' => $body, 'html' => $res];
        }else if($httpInfo['http_code'] == 500 && $json->status == 500){
            return ['head' => $header, 'body' => $body, 'html' => $res];
        }else{
            dump($httpInfo);
            dump($header);
            dump($body);
            throw new \Exception('连接失败');
            die();
        }
    }
    /**
    * 获取数据
    * @param string $cookie  cookie值
    * @param int $page  获取第几页的内容
    */
    public function getdata($cookie, $page)
    {
        $url="https://kdcs.zto.cn/noticeMsg/page";
        $param = [
            "billCode"=> "",
            "endDate"=>date('Y-m-d'),
            "mobile"=> "",
            "pageIndex"=> $page,
            "pageSize"=> 100,
            "path"=> 2,
            "notifyType"    => '0',
            "startDate"=> date('Y-m-d'),
            "status"=> "1",
            "type"=> "0"
        ];
        $data = json_encode($param);
        $headers = array(
            "Content-Type: application/json; charset=utf-8",
            "Content-Length: " . strlen($data),
            "Accept: application/json, text/plain, */*",
            "Accept-Encoding: gzip, deflate, br",
            "Connection: keep-alive",
            "Cookie: " . $cookie,
            "Origin: https://kdcs.zto.cn",
            "Referer: https://kdcs.zto.cn/",
            "User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0",
        );
        $info = $this->http_post_data($url, $data, $headers);//return_code是http状态码
        return $info;
    }

    public function getSession() {
        $url="https://kdcs.zto.cn/#/login";
        $headers = array(
            "Connection: keep-alive",
            "Origin: https://kdcs.zto.cn",
            "Referer: https://kdcs.zto.cn/",
            "User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0",
        );

        $info = $this->http_get_data($url, $headers, true, false);//return_code是http状态码
        if($info['code'] && $info['http_code'] == 200){
            // echo 'getsession: <br/>';
            // dump($info);
            $rex = '/Set-Cookie: .*;/';
            if(preg_match($rex, $info['res'], $matches)){
                $sessionStr = substr($matches[0], 12, 44);
                return $sessionStr;
            }else{
                return false;
            }
        }
    }

    public function getCode($cookie) {
        $url='https://kdcs.zto.cn/nologin/verifyCode?codeType=1&&d=' . microtime();
        $headers = array(
            "Cookie: " . $cookie,
            "Connection: keep-alive",
            "Referer: https://kdcs.zto.cn/",
            "User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0",
        );
        $img = $this->getImg($url, 'static/verifyCode.jpg', $headers);
        return $img;
    }

    /**
    * 导入数据库
    */
    public function importDatabase($param){
        $data = [];
        // 取出数据
        foreach ($param as $item){
            $isEx = ExpressModel::where('billcode', $item['billCode'])
            ->find();
            if(empty($isEx)){
                $data[] = [
                    'phone'         => $item['mobile'],
                    'billcode'      => $item['billCode'],
                    'content'       => $item['content'],
                    'company'       => $item['company'],
                    'company_code'  => $item['companyCode'],
                ];
            }
        }
        try {
            if(!empty($data)){
                $express = new ExpressModel;
                $express->saveAll($data);
            }
            return count($data);
        } catch (\Exception $th) {
            throw $th;
            // return false;
        }
    }

    /**
    * post发送请求
    */
    private function http_post_data($url, $data_string, $headrs, $getHead = false) {
        // dump($data_string);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headrs);
        curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, $getHead);
        // curl_setopt($ch, CURLOPT_NOBODY, $getBody);
        ob_start();
        $res = curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        // dump($res);
        if($res){
            $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            // echo 'post: <br>';
            // dump(curl_getinfo($ch));
            // return array($return_code, $return_content, $res);
            curl_close($ch);
            return ['code'=>1, 'http_code'=>$return_code, 'res'=>$res];
        }else{
            // return curl_error($ch);
            $curlInfo = curl_getinfo($ch);
            // dump($curlInfo);
            $result = ['code'=>0, 'curlinfo'=>$curlInfo, 'error'=>curl_error($ch), 'curl_res'=>$res];
            curl_close($ch);
            return $result;
        }
    }
    /**
    * get 发送请求
    */
    private function http_get_data($url, $headrs, $getHead = false, $getBody = true) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headrs);
        curl_setopt($ch, CURLOPT_HEADER, $getHead);
        curl_setopt($ch, CURLOPT_NOBODY, $getBody);
        ob_start();
        $res = curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        // dump($return_content);
        if($res){
            $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            // return array($return_code, $return_content, $res);
            return ['code'=>1, 'http_code'=>$return_code, 'res'=>$res];
        }else{
            $curlInfo = curl_getinfo($ch);
            $result = ['code'=>0, 'curlinfo'=>$curlInfo, 'error'=>curl_error($ch), 'curl_res'=>$res];
            curl_close($ch);
            return $result;
        }
    }

    
    function getImg($url, $filename, $headers)
    {
        $curl = curl_init();
        $fp = fopen($filename, 'w');
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_FILE, $fp);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLINFO_HEADER_OUT, TRUE);
        $img = curl_exec($curl);
        $info = curl_getinfo($curl);
 
        fclose($fp);
        $size = filesize($filename);
        if ($size) {
            // echo 'getcode: <br>';
            // dump($info);
            curl_close($curl);
            return true;
        } else {
            dump($info);
            throw new \Exception('获取验证码失败');
            return false;
        }
    }
    function getImg2($url, $filename, $cookie)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $cookie);
        $img = curl_exec($curl);
        $info = curl_getinfo($curl);
        dump($img);
        // $size = filesize($filename);
        // if ($size) {
        //     return true;
        // } else {
        //     dump($info);
        //     throw new \Exception('获取验证码失败');
        //     return false;
        // }
    }
}